package com.societyGames.flashForms
{
	import com.societyGames.system.EventObject;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;

	public class HorizontalStackContainer extends Sprite implements IChangeSize
	{
		private var _desiredHeight:Number;
		private var _desiredWidth:Number;
		private var _sizeChangedEventObject:EventObject;
		private var _items:Vector.<DisplayObject> = new Vector.<DisplayObject>();

		public function HorizontalStackContainer()
		{
			this._sizeChangedEventObject = new EventObject(this, "SIZE_CHANGED");
		}

		public function addItem(item:DisplayObject):void
		{	
			var index:int = _items.indexOf(item);
			//If we don't already have it.
			if (index == -1)
			{
				//Add to the vector.
				_items.push(item);
				//Add to display list.
				this.addChild(item);
				//Recalculate graphics.
				calculate();
			}
		}
		
		public function removeItem(item:DisplayObject):void
		{
			var index:int = this._items.indexOf(item);
			if (index != -1)
			{
				this._items.slice(index, 1);
				this.removeChild(item);
				calculate();
			}
		}
		
		public function clearItems():void
		{
			for each (var item:DisplayObject in this._items)
			{
				this.removeChild(item);
			}
			this._items.length = 0;
			calculate();
		}
		
		//Make all of the items in _items appear correctly.
		private function calculate():void
		{
			var nextX:Number = 0;
			for each (var item:DisplayObject in this._items)
			{
				item.x = nextX;
				item.y = 0;	
				nextX += item.width;
			}
			calculateHeight();
			this._sizeChangedEventObject.dispatchEvent();
		}
		
		private function calculateHeight():void
		{
			for each (var item:DisplayObject in this._items)
			{
				item.height = this._desiredHeight;
			}
		}
		
		//IChangeSize-->
		public function get sizeChangedEventObject():EventObject
		{
			return this._sizeChangedEventObject;	
		}
		//<--IChangeSize
		
		public override function set height(value:Number):void
		{	
			if (value != this._desiredHeight)
			{
				this._desiredHeight = value;
				calculateHeight();
			}
		}
		
		//The width is pretty much ignored. Perhaps we should try to scale everything down equally to match the width?
		public override function set width(value:Number):void
		{
			if (value != this._desiredWidth)
			{
				this._desiredWidth = value;
			}
		}
	}
}